<?php namespace Admin\Controller;

//分类控制器
class CateController extends CommonController{
	//存放模型对象
	private $cateModel;
	public function __auto(){
		$this->cateModel=new \Common\Model\Cate;
	}

	//显示分类列表
	public function index(){
		//获取所有数据
		$data=$this->cateModel->orderBy('csort','ASC')->get();
		//判断分类是否为空
		if (!$data) View::error('请先添加分类',U('addCate'));
		//将数据转为树状图
		$dataTree=Data::tree($data,'cname','cid','pid');
		View::with('dataTree',$dataTree)->make();
	}


	//添加分类
	public function addCate(){
		if (IS_POST) {
			if (!$this->cateModel->store()) View::error($this->cateModel->getError());
			View::success('添加成功',U('index'));
		}
		//获取所有数据
		$data=$this->cateModel->orderBy('csort','ASC')->get();
		//将数据转为树状图
		$dataTree=Data::tree($data,'cname','cid','pid');
		View::with('dataTree',$dataTree)->make();
	}

	//添加子分类
	public function addSon(){
		if (IS_POST) {
			if (!$this->cateModel->store()) View::error($this->cateModel->getError());
			View::success('添加成功',U('index'));
		}
		//获得该条数据
		$cid=Q('get.cid',0,'intval');
		$cate=$this->cateModel->where("cid=$cid")->find();
		View::with('cate',$cate)->make();
	}

	//删除分类
	public function del(){
		//获得该条数据
		$cid=Q('get.cid',0,'intval');
		//判断该分类下面有没有职位
		$jobModel=new \Common\Model\Job;
		$jobData=$jobModel->where("category_cid=$cid")->find();
		if ($jobData) View::error('请先下线该分类下的职位');
		//如果分类下有子分类
		$pid=$this->cateModel->where("cid=$cid")->pluck('pid');
		$this->cateModel->where("pid=$cid")->update(['pid'=>$pid]);
		//删除分类
		$this->cateModel->where("cid=$cid")->delete();
		View::success('删除成功');
	}

	//编辑分类
	public function edit(){
		if (IS_POST) {
			if (!$this->cateModel->edit()) View::error($this->cateModel->getError());
			View::success('修改成功',U('index'));
		}
		//获得该条数据
		$cid=Q('get.cid',0,'intval');
		$data=$this->cateModel->where("cid=$cid")->find();
		View::with('data',$data);
		//获得除了自己和自己子集的树桩分类
		$dataTree=Cache::get('cateTree');
		if (!$dataTree) {
			$dataTree=Data::tree($this->cateModel->notMy($cid),'cname','cid','pid');
			Cache::set('cateTree',$dataTree,0);
		}
		View::with('dataTree',$dataTree)->make();
	}

}